import pymongo
import utils

triples = utils.load_csv("./triples.v7.txt")
triples_attr = utils.load_csv("./attrs.v7.txt")

ent = [e for tri in triples for e in tri[:2]]
ent = list(set(ent))
ent_doc = [{"name":e} for e in ent]
i = 0

print(len(ent_doc))
client = pymongo.MongoClient("127.0.0.1:27017")
db = client.mathKG

# print("Make New DB Finish")

entity = db.entity
ment2ent = db.ment2ent
triple_rel = db.triple_rel
triple_attr = db.triple_attr
user = db.user

entity.drop()
print("Drop entity finish")
ment2ent.drop()
print("Drop ment2ent finish")
triple_rel.drop()
print("Drop triple rel finish")
triple_attr.drop()
print("Drop triple attr finish")


p_result = triple_rel.find_one({"p":"先导知识"})
ent_result = entity.find_one({"name":"数与代数"})
ment_result = ment2ent.find_one({"m":"数与代数"})

if not p_result:
	print("drop triple rel clear")
else:
	print(p)
if not ent_result:
	print("drop entity clear")
else:
	print(ent_result)
if not ment_result:
	print("drop ment2ent finish")
else:
	print(ment_result)

print("Start Insert entity...")

entity.create_index([("name",1)], unique=True)

try:
    entity.insert_many(ent_doc)
except pymongo.errors.BulkWriteError as bwe:
    print(bwe.details)
    exit(-1)
print("Insert Finish")

for _,e in enumerate(ent):
    eid = entity.find_one({"name":e})
    if not eid:
        print(e, eid)
    eid = str(eid["_id"])
    ment2ent.insert_one({"m":e, "eid":eid})

appendix_m2e = [{"m":"人教版小学数学三年级上册","e":"人教版小学数学（三年级上册）"},
				{"m":"人教版小学数学三年级下册","e":"人教版小学数学（三年级下册）"},
				{"m":"人教版小学数学四年级上册","e":"人教版小学数学（四年级上册）"},
				{"m":"人教版小学数学四年级下册","e":"人教版小学数学（四年级下册）"}]
print("Insert triples...")


for tri in triples:
    try:
        h,t,r = tri
    except:
        print(tri)
        exit()
    h_id = str(entity.find_one({"name":h})["_id"])
    t_id = str(entity.find_one({"name":t})["_id"])
    triple_rel.insert_one({"sid":t_id, "p":r, "oid":h_id})

# for (e,e_t) in ent:
#     sid = entity.find_one({"name":e})
#     if not sid:
#         print(e, sid)
#     sid = str(sid["_id"])
#     triple_attr.insert_one({"sid":sid, "p":"实体类别", "o":e_t})

for tri in triples_attr:
    h,r,t = tri
    try:
        h_id = str(entity.find_one({"name":h})["_id"])
    except Exception as e:
        print(h,r,t)
        print(e)
    triple_attr.insert_one({"sid":h_id, "p":r, "o":t})

user.insert_one({"username":"admin","password":"admin123"})
print('insert user')